package com.daxue.bootckafka.consume;

import com.daxue.bootckafka.send.TestMessageSender;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author daxue0929
 * @date 2022/10/24
 */

@Service
@Slf4j
public class CommonConsume {


    /**
     * 只有一个消费组，发布订阅模式之点对点传输
     * @param record
     * @param ack
     * @param topic
     */
    @KafkaListener(topics = TestMessageSender.TEST_TOPIC, groupId = TestMessageSender.TEST_TOPIC_GROUP_ID)
    public void topicTest(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("--------================--------");
            log.warn(TestMessageSender.TEST_TOPIC + " 消费了： Topic:" + topic + ",Message:" + msg);
            log.info("--------================--------");
            ack.acknowledge();
        }
    }


}
